package com.zytlifeservice.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by Taxi on 2017/7/19.
 */

public class SignUtils {
    private static final Logger logger = LoggerFactory.getLogger(SignUtils.class);

    //这里的key是根据时间戳的后20位加盐处理。加盐规则自己定。
    public static String generateSignature(Map<String, String> data, String key) throws Exception {
        StringBuffer sb = getStringBuffer(data);
        sb.append("key=").append(key);
        //统一用md5值进行加密处理。
        logger.info("md5验证前的内容={}", sb.toString().toUpperCase());
        return MD5(sb.toString()).toUpperCase();
    }

    public static StringBuffer getStringBuffer(Map<String, String> data) {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuffer sb = new StringBuffer();
        String[] goalArray = keyArray;
        int length = keyArray.length;
        for (int i = 0; i < length; i++) {
            String k = goalArray[i];
            if (!k.equals("sign") && (data.get(k)).trim().length() > 0) {
                sb.append(k).append("=").append((data.get(k)).trim()).append("&");
            }
        }
        return sb;
    }


    public static String MapToString(Map<String, String> data) {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuffer sb = new StringBuffer();
        String[] goalArray = keyArray;
        for (int i = 0; i < goalArray.length; i++) {
            String key = goalArray[i];
            if (data.get(key).trim().length() > 0) {
                sb.append(key).append("=").append(data.get(key).trim()).append("&");
            }
        }
        return sb.substring(0, sb.length() - 1);
    }

    public static Map<String, String> StringToMap(String content) {
        Map<String, String> map = new HashMap<>();
        String[] split = content.split("&");
        for (String s : split) {
            String[] rs = s.split("=");
            if (rs.length == 2) {
                map.put(rs[0], rs[1]);
            } else {
                if (rs.length != 0) {
                    map.put(rs[0], "");
                }
            }
        }
        return map;
    }


    public static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        byte[] var4 = array;
        int var5 = array.length;

        for (int var6 = 0; var6 < var5; ++var6) {
            byte item = var4[var6];
            sb.append(Integer.toHexString(item & 255 | 256).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

}
